package com.pangu.config.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author Linbizhao
 * @description:
 * @since 2023/11/23 15:22
 */
@Slf4j
@EnableKafka
@Configuration
public class UpstreamMessageKafkaConfig {


    @Value("${threadPool.upstream.core:32}")
    private Integer upstreamTaskExecutorCoreNum;

    @Value("${threadPool.upstream.max:64}")
    private Integer upstreamTaskExecutorMaxNum;

    @Value("${threadPool.upstream.queueCapacity:1024}")
    private Integer upstreamTaskExecutorQueueCapacity;

    /**
     * 上行消息配置业务处理线程池
     *
     * @return 线程池
     */
    @Bean("upstreamTaskExecutor")
    public TaskExecutor upstreamTaskExecutor() {
        return createThreadPoolTaskExecutor("equipment-upstream-task-", upstreamTaskExecutorCoreNum, upstreamTaskExecutorMaxNum,
                upstreamTaskExecutorQueueCapacity);
    }

    private ThreadPoolTaskExecutor createThreadPoolTaskExecutor(String prefix, int corePoolSize, int maxPoolSize, int queueCapacity) {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(prefix);
        executor.setRejectedExecutionHandler(
                (r, executor1) -> log.error("task executor rejectedExecution , Runnable Class : {}", r.getClass().getSimpleName()));
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.initialize();
        log.info("[{}]TaskExecutor 初始化成功. core[{}] max[{}] queueCapacity[{}]", prefix, corePoolSize, maxPoolSize, queueCapacity);
        return executor;
    }
}
